﻿using CommunityToolkit.Mvvm.ComponentModel;
using System.Text;

namespace MauiAndroidBluetoothTest.Models
{
    public sealed partial class AppendableString : ObservableObject
    {
        [ObservableProperty]
        int limit;

        public string StringValue => this.builder.ToString();

        private readonly StringBuilder builder;
        public AppendableString(int limit = -1)
        {
            this.Limit = limit;
            this.builder = new StringBuilder();
        }

        private void Cut()
        {
            if (limit < 0)
                return;

            var delta = builder.Length - limit;
            if (delta <= 0)
                return;

            _ = builder.Remove(0, delta);
        }

        public AppendableString Append(string s)
        {
            this.OnPropertyChanging(nameof(StringValue));
            _ = builder.Append(s);
            Cut();
            this.OnPropertyChanged(nameof(StringValue));
            return this;
        }

        public AppendableString AppendLine()
        {
            this.OnPropertyChanging(nameof(StringValue));
            _ = builder.AppendLine();
            Cut();
            this.OnPropertyChanged(nameof(StringValue));
            return this;
        }

        public AppendableString AppendLine(string s)
        {
            this.OnPropertyChanging(nameof(StringValue));
            _ = builder.AppendLine(s);
            Cut();
            this.OnPropertyChanged(nameof(StringValue));
            return this;
        }

        public override string ToString()
        {
            return StringValue;
        }
    }
}
